<template>
  <div class="club-member-management">
    <h2>社团成员管理</h2>
    
    <!-- 搜索表单 -->
    <div class="search-form">
      <el-form :inline="true" :model="queryParams" @submit.prevent>
        <el-form-item label="社团" >
          <el-select v-model="queryParams.clubId" placeholder="请选择社团" clearable
                    filterable >
            <el-option 
              v-for="club in clubOptions" 
              :key="club.id" 
              :label="club.name"
              :value="club.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="成员姓名">
          <el-input v-model="queryParams.userName" placeholder="请输入成员姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态"style="width: 200px">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="待审核" value="pending"></el-option>
            <el-option label="已通过" value="approved"></el-option>
            <el-option label="已拒绝" value="rejected"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    
    <!-- 操作按钮 -->
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd" v-if="isAdmin || isClubLeader">添加成员</el-button>
    </div>
    <div class="operation-container">
      <el-button type="primary" @click="handleAdd" v-if="isStudent">申请入团</el-button>
    </div>
    
    <!-- 成员表格 -->
    <el-table v-loading="loading" :data="memberList" border stripe style="width: 100%">
      <el-table-column prop="id" label="ID" width="60"></el-table-column>
      <el-table-column label="社团名称" width="180">
        <template #default="scope">
          {{ scope.row.club ? scope.row.club.name : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="成员姓名" width="120">
        <template #default="scope">
          {{ scope.row.user ? (scope.row.user.realName || scope.row.user.username) : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="联系邮箱" width="220">
        <template #default="scope">
          {{ scope.row.user ? scope.row.user.email : '-' }}
        </template>
      </el-table-column>
      <el-table-column label="联系电话" width="150">
        <template #default="scope">
          {{ scope.row.user ? scope.row.user.phone : '-' }}
        </template>
      </el-table-column>
      <!-- <el-table-column prop="points" label="积分" width="80"></el-table-column> -->
      <el-table-column prop="status" label="状态" width="130">
        <template #default="scope">
          <el-tag :type="getMemberStatusType(scope.row.status)">
            {{ formatMemberStatus(scope.row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="joinDate" label="加入日期" width="200">
        <template #default="scope">
          {{ formatDate(scope.row.joinDate) }}
        </template>
      </el-table-column>
     <el-table-column label="操作" fixed="right" width="180">
  <template #default="scope">
    <!-- 编辑按钮 -->
    <el-button
      v-if="
        (isAdmin) ||
        (isClubLeader &&
          isManagedClub(scope.row.clubId) &&
          scope.row.userId !== userInfo.id)  // 负责人不显示自己的操作
      "
      link
      type="primary"
      @click="handleEdit(scope.row)"
    >
      编辑
    </el-button>

    <!-- 删除按钮 -->
    <el-button
      v-if="
        (isAdmin) ||
        (isClubLeader &&
          isManagedClub(scope.row.clubId) &&
          scope.row.userId !== userInfo.id)  // 负责人不显示自己的操作
      "
      link
      type="danger"
      @click="handleDelete(scope.row)"
    >
      移除
    </el-button>
  </template>
</el-table-column>

    </el-table>
    
    <!-- 分页组件 -->
    <div class="pagination-container">
      <el-pagination
        :current-page="queryParams.page"
        :page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getClubMemberList, deleteClubMember } from '@/api/clubMember'
import { getClubList } from '@/api/club'
import { useUserStore } from '@/store/user'

const router = useRouter()
const userStore = useUserStore()
const loading = ref(false)
const memberList = ref([])
const total = ref(0)
const clubOptions = ref([])

// 用户信息
const userInfo = computed(() => userStore.userInfo)
const isAdmin = computed(() => userInfo.value.role === 'admin')
const isClubLeader = computed(() => userInfo.value.role === 'club_leader')
const isStudent = computed(() => userInfo.value.role === 'student')

// 判断当前社团负责人是否管理指定社团
const isManagedClub = (clubId) => {
  if (!clubId || !isClubLeader.value) return false
  return clubOptions.value.some(club => club.id === clubId && club.leaderId === userInfo.value.id)
}

// 查询参数
const queryParams = reactive({
  page: 1,
  pageSize: 10,
  clubId: null,
  userName: '',
  status: '',
  userId: null
})

// 获取社团成员列表
const getList = async () => {
  loading.value = true
  try {
    // 如果是学生，只能查看自己的记录
    if (isStudent.value) {
      queryParams.userId = userInfo.value.id
    }
    // 如果是社团负责人，只能查看自己管理的社团
    else if (isClubLeader.value && !isAdmin.value) {
      // 根据登录用户信息查询其管理的社团
      const userClubs = clubOptions.value.filter(club => club.leaderId === userInfo.value.id)
      if (userClubs.length > 0) {
        if (!queryParams.clubId) {
          // queryParams.clubId = userClubs[0].id // 默认查询第一个社团
        } else if (!userClubs.some(club => club.id === queryParams.clubId)) {
          ElMessage.error('您无权查看此社团的成员')
          loading.value = false
          return
        }
      }
    }
    
    const res = await getClubMemberList(queryParams)
    if (res.data && res.code === 200) {
      memberList.value = res.data.list
      total.value = res.data.total
    } else {
      ElMessage.error(res.message || '获取社团成员列表失败')
    }
  } catch (error) {
    console.error('获取社团成员列表出错:', error)
    ElMessage.error('获取社团成员列表失败')
  } finally {
    loading.value = false
  }
}

// 加载社团列表
const loadClubs = async () => {
  try {
    const res = await getClubList({ pageSize: 1000 })
    if (res.data && res.code === 200) {
      clubOptions.value = res.data.list
    }
  } catch (error) {
    console.error('获取社团列表出错:', error)
    ElMessage.error('获取社团列表失败')
  }
}

// 搜索
const handleSearch = () => {
  queryParams.page = 1
  getList()
}

// 重置
const handleReset = () => {
  queryParams.clubId = null
  queryParams.userName = ''
  queryParams.status = ''
  
  // 如果是学生，保持userId筛选条件
  if (isStudent.value) {
    queryParams.userId = userInfo.value.id
  } else {
    queryParams.userId = null
  }
  
  queryParams.page = 1
  getList()
}

// 添加成员
const handleAdd = () => {
  router.push('/club-members/add')
}

// 编辑成员
const handleEdit = (row) => {
  router.push(`/club-members/edit/${row.id}`)
}

// 删除成员
const handleDelete = (row) => {
  ElMessageBox.confirm(
    `确定要将 ${row.user?.realName || row.user?.username || '该成员'} 从 ${row.club?.name || '社团'} 中移除吗？`,
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(async () => {
    try {
      const res = await deleteClubMember(row.id)
      if (res.code === 200) {
        ElMessage.success('移除成功')
        getList()
      } else {
        ElMessage.error(res.message || '移除失败')
      }
    } catch (error) {
      console.error('删除社团成员出错:', error)
      ElMessage.error('移除失败')
    }
  }).catch(() => {
    ElMessage.info('已取消操作')
  })
}

// 处理每页条数变化
const handleSizeChange = (size) => {
  queryParams.pageSize = size
  getList()
}

// 处理页码变化
const handleCurrentChange = (page) => {
  queryParams.page = page
  getList()
}

// 格式化成员状态
const formatMemberStatus = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}

// 成员状态标签样式
const getMemberStatusType = (status) => {
  const typeMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return typeMap[status] || ''
}

// 日期格式化
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 初始化
onMounted(() => {
  loadClubs()
  getList()
})
</script>

<style scoped>
.club-member-management {
  padding: 20px;
}

.search-form {
  background-color: #f5f7fa;
  padding: 18px;
  border-radius: 4px;
  margin-bottom: 20px;
}

.operation-container {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 